package feng.demo.service;

import feng.demo.dao.CommodityDao;
import feng.demo.dao.OrditemDao;
import feng.demo.entity.Commodity;
import feng.demo.entity.Order;
import feng.demo.entity.Orditem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
@Service
@CacheConfig(cacheNames = {"orditem"})
public class OrditemServiceImpl implements OrditemService{
    @Autowired
    OrditemDao orditemDao;
    @Autowired
    CommodityService commodityService;
    @Override
    @Cacheable
    public List<Orditem> findAll() {
        List<Orditem> list = orditemDao.findAll();
        return doadds(list);
    }

    @Override
    @Cacheable
    public List<Orditem> findOrditem(Map<String, Object> map) {
        List<Orditem> list = orditemDao.findOrditem(map);
        return doadds(list);
    }

    @Override
    @Cacheable(key = "#p0")
    public Orditem findById(Integer itemid) {
        Orditem orditem = orditemDao.findById(itemid);
        return doadd(orditem);
    }

    @Override
    @CacheEvict(value = "orditem", allEntries = true)
    public int add(Orditem orditem) {
        return orditemDao.add(orditem);
    }

    @Override
    @CacheEvict(value = "orditem", allEntries = true)
    public int del(Integer itemid) {
        return orditemDao.del(itemid);
    }

    @Override
    @CacheEvict(value = "orditem", allEntries = true)
    public int update(Orditem orditem) {
        return orditemDao.update(orditem);
    }

    @Override
    @Cacheable
    public List<Orditem> findByordid(Integer ordid) {
        List<Orditem> list = orditemDao.findByordid(ordid);
        return doadds(list);
    }

    private List<Orditem> doadds(List<Orditem>list){
        for (Orditem o:list) {
            Commodity commodity = commodityService.findById(o.getCommodity().getComid());
            o.setCommodity(commodity);
        }

        return list;
    }
    private Orditem doadd(Orditem o){
        Commodity commodity = commodityService.findById(o.getCommodity().getComid());
        o.setCommodity(commodity);
        return o;
    }
}
